<?php
/**
 * Created by PhpStorm.
 * User: zhangbing
 * Date: 2017/6/19 0019
 * Time: 11:11
 */
namespace app\api\controller;
use app\models\Models;
use think\console\command\make\Model;

class Index extends Base{
    /**
     * app首页
     * @return \think\response\Json
     */
    public function index(){
        if(request()->isPost()){
            $user  = new Models('user');
            try{
                // 签名验证,获取参数
                $params = self::paramsSign(['equipment','encrypt','lng','lat','location','page']);
                // 登录状态下
                if($params['token']){
                    // 登录验证
                    $params = self::checkLogin();
                    // 更新用户位置信息
                    self::updateLocation(['lng'=>$params['lng'],'lat'=>$params['lat'],'location'=>$params['location']],['uid'=>$params['uid']]);
                }
                // 获取扫码有效用户
                $scan = self::isScan();
                // 获取用户信息
                $join = [['location b','a.id = b.uid','left'],['account c','a.id = c.uid','left']];
                $field = 'a.id,a.nickname,a.sex,a.birth,a.signature,a.wine,b.lng,b.lat,b.location,(c.recharge+c.cost) sort,a.portrait';
                // 登录情况下自己不可见
                $where = $params['token'] ? ['a.status'=>Models::STATUS_ON,'a.id'=>['<>',$params['uid']]] : ['a.status'=>Models::STATUS_ON];
                $list = $user->_page($where,$field,'',$join,$params['page']);
                $list = $list->items();
                foreach($list as $k=>$v){
                    $list[$k]['background'] = '';
                    $list[$k]['name']       = '';
                    foreach($scan as $v1){
                        if($v['id'] == $v1['uid']){
                            $list[$k]['background'] = empty($v1['background']) ? '' : self::arrayMapBackground($v1['background']);
                            $list[$k]['name']       = $v1['name'];
                        }
                    }
                    $list[$k]['portrait']   = empty($v['portrait']) ? '' : self::arrayMapPortrait($v['portrait']);
                    $list[$k]['age']        = calcAge($v['birth']);
                    $list[$k]['distance']   = getDistance($v['lng'],$v['lat'],$params['lng'],$params['lat']);
                    // 删除多余元素
                    unset($list[$k]['lng'],$list[$k]['lat'],$list[$k]['birth']);
                }
                $distance = array_column($list,'distance');   // 获取列数据
                $sort     = array_column($list,'sort');       // 获取列数据
                array_multisort($distance,SORT_ASC,$sort,SORT_DESC,$list);    // 多维数组的排序
            } catch (\Exception $e){
                return json(self::formatResult($e->getCode(),$e->getMessage()));
            }
            return json(self::formatSuccessResult($list));
        }
    }
}